package logic

import (
	"context"
	"fmt"
	"zkzk2/models/mysql"
	"zkzk2/models/redis"
	"zkzk2/pkg"

	"zkzk2/zk2rpc/internal/svc"
	"zkzk2/zk2rpc/zk2rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *zk2rpc.UpdateRequest) (*zk2rpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	sendsms := redis.Client.Get("sendsms" + in.Tel + in.Source)
	if sendsms.Val() != in.Sendsms {
		return nil, fmt.Errorf("短信未验证,请重新输入")
	}

	var update mysql.User
	mysql.DB.Where("id = ?", in.Id).Find(&update)

	if update.Password == pkg.Md5(in.Oldpassword) {
		return nil, fmt.Errorf("修改失败")
	}
	if in.Password == pkg.Md5(in.Newpassword) {
		return nil, fmt.Errorf("两次密码输入不一致")
	}
	update.Password = pkg.Md5(in.Password)
	mysql.DB.Debug().Model(&update).Updates(&update)

	redis.Client.Del("sendsms" + in.Tel + in.Source)
	return &zk2rpc.UpdateResponse{Id: int64(update.ID)}, nil
}
